﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using UIWindow.Domains;
using UIWindow.Entitys;
using UIWindow.Enums;
using UIWindow.GlobalParameters;
using UIWindow.Helper;
using UIWindow.Services.Context;

namespace UIWindow.Services.Handle
{
    public class ScanCode : TaskEventBase<ScanCodeContext>,Lucifer.ITaskEvent<ScanCodeContext>
    {
        private ParameterGlobal _parameter;
        private HomePageGlobal _homePage;
        private DeviceGlobal _device;
        private UserGlobal _user;
        public ScanCode(ParameterGlobal parameter, HomePageGlobal homePage, DeviceGlobal device, UserGlobal userGlobal)
        {
            _parameter = parameter;
            _homePage = homePage;
            _device = device;
            _user = userGlobal;
        }

        public override Task Handle(ScanCodeContext context)
        {
            $"前扫码启动".RunLog(MessageLevelType.Info, "message");
            var plc = _device.DeviceList.FirstOrDefault(t => t.Types == DeviceType.注液机).Comm;
            ProductionData.Meta.TableName = $"ProductionData_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}";
            string barcode = null;
            //if (!string.IsNullOrEmpty(context.BarCode)) barcode = Regex.Match(context.BarCode, _parameter.RunParameter.BarcodeRules, RegexOptions.Singleline).Value;
            DateTime dateTime = DateTime.Now;
            if (context.BarCode == null)
            {
                //自动扫码
                var device = _device.DeviceList.FirstOrDefault(x => x.Types == DeviceType.自动扫码);
                device.Comm.Write(new byte[] { 0x16, 0x54, 0x0d});//开始
                barcode = Regex.Match(Encoding.Default.GetString(device.Comm.Read()), _parameter.RunParameter.BarcodeRules).Value;
                device.Comm.Write(new byte[] { 0x16, 0x55, 0x0d });//停止
                $"自动扫码枪条码：{barcode}".RunLog(MessageLevelType.Info);
                if (string.IsNullOrEmpty(barcode))
                {
                    $"自动条码规则认证失败,请手持扫码！！！".MessageDialogsUI(MessageLevelType.Error);
                    _homePage.HomeProperty.ScanCodeNG += 1;
                    _homePage.HomeProperty.NGTotal += 1;
                    _homePage.HomeProperty.Total += 1;
                    return base.Handle(context);
                }
            }
            else
            {
                barcode = Regex.Match(context.BarCode, _parameter.RunParameter.BarcodeRules, RegexOptions.Singleline).Value;
                if (string.IsNullOrEmpty(barcode))
                {
                    $"手持扫码失败，请继续手持扫码，直到扫码成功为止！！！".MessageDialogsUI(MessageLevelType.Error);
                    _homePage.HomeProperty.ScanCodeNG += 1;
                    _homePage.HomeProperty.NGTotal += 1;
                    _homePage.HomeProperty.Total += 1;
                    TaskManager.RemoveTask(context);
                    return Task.CompletedTask;
                }
            }
            byte[] byteBar = Encoding.ASCII.GetBytes(barcode);
            MemoryStream memoryStream = new MemoryStream();
            memoryStream.WriteByte(0x32);
            memoryStream.WriteByte((byte)byteBar.Length);
            memoryStream.Write(byteBar, 0, byteBar.Length);
            memoryStream.Close();
            if (plc.Write(new Models.S7NET.S7ParamModel() { Address = context.AddressBarCode, Value = memoryStream.ToArray() }))
            {
                DataThis:
                ProductionData entity = ProductionData.Find(ProductionData._.BarCode == barcode);
                if (entity == null)
                {
                    if (dateTime.ContrastTime())
                    {
                        dateTime = dateTime.AddMonths(-1);
                        goto DataThis;
                    }
                    if (_parameter.DecideParameter.EnableMES
                        && !MyMesHelper.GroupTest(barcode, _parameter.RunParameter.EquipNum, _user.LoginUser.Name, _parameter.RunParameter.MoNumber, _parameter.RunParameter.GroupName, _parameter.MESParameter.GroupTestNumber)) 
                    {
                        $"条码：{barcode} 工序校验功能结果：不可入站！！！".MessageDialogsUI(MessageLevelType.Error);
                        return base.Handle(context);
                    }
                    if (_parameter.DecideParameter.EnableMES
                        && !MyMesHelper.CellBOMItemsCheck(barcode,
                        _parameter.RunParameter.MoNumber,
                        _user.LoginUser.Name,
                        _parameter.RunParameter.EquipNum, $"|{_parameter.RunParameter.ElectrolyteMaterialNumber}:{_parameter.RunParameter.BatchElectrolyte};{_parameter.RunParameter.BatchElectrolyteNumber}", 3))
                    {
                        $"条码：{barcode} 电解液条码验证不通过！！！".MessageDialogsUI(MessageLevelType.Error);
                        return base.Handle(context);
                    }
                    entity = new ProductionData()
                    {
                        UserName = _user.LoginUser.Name,
                        BarCode = barcode,
                        Stage = 1,
                        FrontScanTime = DateTime.Now,
                        AfterWeighingRange = $"{_parameter.WeighingParameter.WeighAfterFilling - _parameter.WeighingParameter.FluctuationWeighAfterFilling }-{_parameter.WeighingParameter.FluctuationWeighAfterFilling + _parameter.WeighingParameter.WeighAfterFilling}",
                        ForeweighRange = $"{_parameter.WeighingParameter.WeighBeforeFilling - _parameter.WeighingParameter.FluctuationWeighBeforeFilling}-{_parameter.WeighingParameter.WeighBeforeFilling + _parameter.WeighingParameter.FluctuationWeighBeforeFilling}",
                        FluidRateRange = $"{_parameter.WeighingParameter.InjectionVolume - _parameter.WeighingParameter.FluctuationInjectionVolume}-{_parameter.WeighingParameter.InjectionVolume + _parameter.WeighingParameter.FluctuationInjectionVolume}",
                        BatchElectrolyte = _parameter.RunParameter.BatchElectrolyte,
                        ElectrolyteWaterContent = _parameter.RunParameter.ElectrolyteWaterContent,
                        HydrofluoricAcidContent = _parameter.RunParameter.HydrofluoricAcidContent,
                        EquipmentIdentity = _parameter.RunParameter.EquipNum,
                        MesUpdateMode = _parameter.DecideParameter.EnableMES,
                        ElectrolyteMaterialNumber = _parameter.RunParameter.ElectrolyteMaterialNumber,
                        MoNumber = _parameter.RunParameter.MoNumber,
                        GroupCode= _parameter.RunParameter.GroupCode,
                        GroupName= _parameter.RunParameter.GroupName,
                    };
                    entity.Insert();
                    _homePage.ScanCodeBeforeList.Insert(0, new Models.ProductionDataModel()
                    {
                        FrontScanTime = DateTime.Now,
                        BarCode = barcode,
                        ProductBatch = _parameter.RunParameter.BatchNumber,
                    });
                    _homePage.HomeProperty.Total += 1;
                }
                else
                {
                    entity.Stage = entity.Stage == 1 ? 2 : 3;
                    switch (entity.Stage)
                    {
                        case 1: "一次扫码".RunLog(MessageLevelType.Info, "message"); break;
                        case 2: "二次扫码".RunLog(MessageLevelType.Info, "message"); break;
                        case 3: "三次扫码".RunLog(MessageLevelType.Info, "message"); break;
                    }
                    if (entity.Stage == 2) entity.BackScanTime = DateTime.Now;
                    entity.Update();
                    _homePage.ScanCodeRearList.Insert(0, new Models.ProductionDataModel()
                    {
                        BarCode = barcode,
                        ProductBatch = _parameter.RunParameter.BatchNumber,
                    });
                }
            }
            else
            {
                $"扫码写入失败,请重新扫码!!!".MessageDialogsUI(MessageLevelType.Error);
            }
            return base.Handle(context);
        }


    }
}
